﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace INF1010_Chat
{
    public class GroupList
    {
        private List<Group> groups;

        public GroupList()
        {
            groups = new List<Group>();
        }

        public List<Group> Groups
        {
            get
            {
                return groups.ToList();
            }
        }

        public Group AddGroup(string groupName)
        {
            Group group = null;
            if (!groups.Select(g => g.Name).Contains(groupName))
            {
                group = new Group(groupName);
                groups.Add(group);
            }

            return group;
        }

        public void RemoveGroup(string groupName)
        {
            Group group = groups.FirstOrDefault(g => g.Name.Equals(groupName));
            if (group != null)
            {
                groups.Remove(group);
            }
        }

        public string Serialize()
        {
            string result = String.Empty;
            if (groups.Any())
                result = String.Join("%?&", groups.Select(u => u.Serialize()));
            return result;
        }

        public static GroupList Deserialize(String source)
        {
            List<string> groupsName = source.Split("%?&".ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
            GroupList groupList = new GroupList();
            foreach (string groupName in groupsName)
            {
                Group group = Group.Deserialize(groupName);
                groupList.groups.Add(group);
            }
            return groupList;
        }
    }
}
